<?php
/**
 * User: aka
 * Date: 2018/6/24
 * Time: 16:38
 */

namespace app\backstage\model;


use app\common\db\DbOperation;
use app\common\hash\EncodeOperation;
use think\Session;

class User
{
    static private $adminUser = 'admin_user';

    public $encodeOperation;
    public $dbOperation;

    public function __construct()
    {
        $this->dbOperation = new DbOperation();
        $this->encodeOperation = new EncodeOperation();
    }

    public function __destruct()
    {
        unset($this->dbOperation);
        unset($this->encodeOperation);
    }

    private function getDbOperation() : DbOperation
    {
        return $this->dbOperation;
    }

    private function getEncodeOperation() : EncodeOperation
    {
        return $this->encodeOperation;
    }

    private function getUserSalt(string $email) : string
    {
        $email = $this->getEncodeOperation()->getEncodeEmail($email,'aka');
        $result = $this->getDbOperation()->find(self::$adminUser,['email'=>$email]);
        return !empty($result) ? $result['salt'] : '';
    }

    public function login(array $requestData) : bool
    {
        $userData = $this->findUserData($requestData);
        Session::set('user',['email'=>$requestData['email'],'ip'=>$requestData['login_ip']]);
        return !empty($userData) ? $this->updateUserData($userData,$requestData) : false ;
    }

    private function findUserData(array $requestData) : array
    {
        $salt = $this->getUserSalt($requestData['email']);
        $email = $this->getEncodeOperation()->getEncodeEmail($requestData['email'],'aka');
        $password = $this->getEncodeOperation()->getEncodePassword($salt,$requestData['password'],'aka');
        $result = $this->getDbOperation()->find(self::$adminUser,['email'=>$email,'password'=>$password]);
        return !empty($result) ? $result : [];
    }

    private function updateUserData(array $userData,array $requestData) : bool
    {
        $result = $this->getDbOperation()->update(self::$adminUser,$userData['id'],['login_time'=>time(),'login_ip'=>$requestData['login_ip']]);
        return $result ? true : false;
    }

    public function changeUserPasswordAction(array $requestData) : bool
    {
        $userSession = Session::get('user');
        $email = $this->getEncodeOperation()->getEncodeEmail($userSession['email'],'aka');
        $salt = $this->getUserSalt($userSession['email']);
        $oldPassword = $this->getEncodeOperation()->getEncodePassword($salt,$requestData['password_old'],'aka');
        $newPassword = $this->getEncodeOperation()->getEncodePassword($salt,$requestData['password'],'aka');
        $userData = $this->getDbOperation()->find(self::$adminUser,['email'=>$email]);
        $result = $oldPassword == $userData['password'];
        return $result ? $this->getDbOperation()->update(self::$adminUser,$userData['id'],['password'=>$newPassword]) :false;
    }
}